<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/6 0006
 * Time: 下午 2:17
 */

namespace DataAPI\Controller;

use DataAPI\Extend\ExtendApi;
use DataAPI\Model\GoodSyncLogModel;
use DataAPI\Model\SupplierProductsModel;
use Think\Controller;

class SyncController extends Controller
{
    private $appId ;//= '10002';
    private $appKey ;// ='Ukk4t40pR58ldy48vP694uOnBwsDotqJVP06V1dIma05xmj5ZT';
    protected $model;
    private $api;
    function __construct($appID,$appKey)
    {
        set_time_limit(0);
        $this->appId = session('app_id');
        $this->appKey = session('app_key');
        $this->model = M('supplier_products');
        $this->api = new ExtendApi($this->appId,$this->appKey);
    }

    public function index(){
    }

    /**
     * @param $batch
     * 同步Excel
     */
    public function syncExcel($batch){
        $goods = M('test_supplier_products')->where(['is_sync'=>'0','batch'=>$batch])->select();
        $this->eachGoods($goods);
        M('sync_excel')->where(['is_sync'=>'0','batch'=>$batch])->save(['is_sync'=>'1','synctime'=>date("Y-m-d H:i:s",time())]);
    }

    public function syncGoods(){
        $goods = $this->model->where(['is_sync'=>'0'])->order('id DESC')->limit(70,20)->select();
        foreach ($goods  as $v)
        {
            unset($v['app_id'],$v['is_sync'],$v['b_id'],$v['createdtime']);
            $res =  $this->api->goodsAdd($v);
            if ($res['code'] == 200){
                $this->model->where(['earn13'=>$v['earn13']])->save(['is_sync'=>'1']);
                echo $res['code'].$res['msg'];
            }
            else
            {
                var_dump($this->api->getError());
            }
        }
    }

    /**
     *按需单个同步商品
     */
    public function syncOneGoods($id){
        $goods = $this->model->where(['id'=>$id])->select();
       $this->eachGoods($goods);
    }
    public function eachGoods($goods){
        foreach ($goods  as $v)
        {
            unset($v['app_id'],$v['is_sync'],$v['b_id'],$v['createdtime']);
            $res =  $this->api->goodsAdd($v);
            $Logs = new GoodSyncLogModel();
            $data['goodName'] = $v['name'];
            $data['goodId'] = $v['id'];
            if ($res['code'] == 200){
                $this->model->where(['earn13'=>$v['earn13'],'app_id'=>$this->appId])->save(['is_sync'=>'1']);
                $data['value'] = '商品《'.$v['name']."》同步成功";
                $Logs->addLog($data);
                return true;
            }
            else
            {
                $data['value'] = '商品《'.$v['name']."》同步失败";
                $Logs->addLog($data);
                return $res['msg'];
            }
        }
    }
}